package com.winit.openapi.es.manager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.elasticsearch.action.ActionFuture;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.admin.indices.get.GetIndexResponse;
import org.elasticsearch.client.Client;
import org.springframework.stereotype.Service;

@Service("esAdminManager")
public class EsAdminManager {

    @Resource
    private Client esClient;

    public String [] queryAllValidIndexName(String[] possibleIndexs) {
        ActionFuture<GetIndexResponse> future = esClient.admin().indices().getIndex(new GetIndexRequest());
        GetIndexResponse response = future.actionGet();
        String[] actualIndexs = response.getIndices();

        if (null == actualIndexs || actualIndexs.length == 0) {
            return null;
        }

        if (null == possibleIndexs || possibleIndexs.length == 0) {
            return null;
        }
        List<String> actualIndexList = Arrays.asList(actualIndexs);

        List<String> expectIndexList = new ArrayList<String>();

        for (int i = 0 ; i < possibleIndexs.length ; i++) {

            for (String index : actualIndexList) {
                if (possibleIndexs[i].equals(index)) {
                    expectIndexList.add(possibleIndexs[i]);
                    break;
                }
            }

        }
        String[] expectIndex = expectIndexList.toArray(new String[expectIndexList.size()]);
        return expectIndex;
    }

}
